import { createSlice } from '@reduxjs/toolkit'
import { formatDate } from '../utils/dateUtils'
import { produce } from 'immer'

export type ChatPropsType = {
  role: string
  reasoning_content?: string // 推理内容
  content: string
  createTime?: string
}

export type ChatListType = {
  key: string
  label: string // 消息名称
  timestamp: number
  group: string // 分组
  chatList: Array<ChatPropsType>
  isInput?: boolean
}

export type initialStateType = {
  // 当前选中的key
  selectedKey: string
  // 消息分组
  messageList: ChatListType[]
  // 是否正在加载
  loading: boolean
  // 当前选中的模型
  selectedModel: string
}

const initialState: initialStateType = {
  messageList: [],
  selectedKey: '',
  loading: false,
  selectedModel: 'qwen-max'
}

export const messageSlice = createSlice({
  name: 'message',
  initialState,
  reducers: {
    // 添加消息
    addMessage: produce((state: initialStateType, action: { payload: string }) => {
      // 获取消息内容
      const chatItem = {
        role: 'user',
        content: action.payload,
        createTime: formatDate('HH:mm:ss')
      }
      // 设置对话的lable
      const getlabel = () => {
        if (chatItem.content.length < 15) {
          return chatItem.content
        } else {
          return chatItem.content.slice(0, 15) + '...'
        }
      }
      // 首先判断这个对话是否是第一次发起
      const existingMessage = state.messageList.find(item => item.key === state.selectedKey)
      if (!existingMessage) {
        const newKey = Date.now() + ''
        state.messageList.unshift({
          key: newKey,
          label: getlabel(),
          timestamp: Date.now(),
          group: formatDate('YYYY-MM-DD'), // 用日期来分组
          chatList: [chatItem]
        })
        // 选中最新的key
        state.selectedKey = newKey
      } else {
        if (existingMessage.chatList.length === 0) {
          existingMessage.label = getlabel()
        }
        // 往chatList中添加消息
        existingMessage.chatList.push(chatItem)
      }
    }),
    // 修改后的 addSystemMessage
    addSystemMessage: produce(
      (
        state: initialStateType,
        action: {
          payload: {
            reasoning_content?: string
            content?: string
          }
        }
      ) => {
        if (!state.selectedKey) {
          console.warn('addSystemMessage: No selected conversation.')
          return // 没有选中的对话，直接返回
        }

        // 找到对话
        const existingConversation = state.messageList.find(item => item.key === state.selectedKey)

        if (existingConversation) {
          const { reasoning_content, content } = action.payload
          let contentToAdd = '' // 用于存储本次调用需要添加或更新的内容

          // 1. 处理推理内容
          if (reasoning_content) {
            contentToAdd = reasoning_content.replace(/\\n/g, '\n') // 替换转义换行符
            // const lines = cleanedReasoning.split('\n') // 按行分割
            // const formattedReasoning = lines.map(line => `> ${line}`).join('\n') // 为每行添加 '> ' 前缀并重新组合
            // contentToAdd += formattedReasoning
          }

          // 2. 处理正式回答的内容
          if (content) {
            contentToAdd = content.replace(/\\n/g, '\n') // 替换转义换行符
            // contentToAdd += cleanedContent
          }

          // 如果本次调用没有提供任何有效内容，则不进行操作
          if (!contentToAdd) {
            return
          }

          // 3. 判断是追加到最后一条系统消息还是新建一条
          const lastMessage =
            existingConversation.chatList.length > 0
              ? existingConversation.chatList[existingConversation.chatList.length - 1]
              : null

          if (lastMessage && lastMessage.role === 'system') {
            // 如果最后一条是系统消息，追加内容
            if (reasoning_content) {
              lastMessage.reasoning_content += contentToAdd
            } else if (content) {
              lastMessage.content += contentToAdd
            }
          } else {
            const newChat: ChatPropsType = {
              role: 'system',
              createTime: formatDate('HH:mm:ss'), // 使用你的 formatDate 函数
              reasoning_content: '',
              content: ''
            }
            // 如果有推理内容，则添加到新的系统消息中
            if (reasoning_content) {
              newChat.reasoning_content = contentToAdd
            } else if (content) {
              newChat.content = contentToAdd
            }
            // 如果最后一条不是系统消息，或者对话为空，则添加新的系统消息
            existingConversation.chatList.push(newChat)
          }
        } else {
          console.warn(`addSystemMessage: Conversation with key ${state.selectedKey} not found.`)
        }
      }
    ),
    // 改变当前选中的key
    changeSelectedKey: produce((state: initialStateType, action: { payload: string }) => {
      state.selectedKey = action.payload
    }),
    // 设置Loading
    setLoading: produce((state: initialStateType, action: { payload: boolean }) => {
      state.loading = action.payload
    }),
    // 新建对话
    addConversation: produce((state: initialStateType) => {
      // 如果已经是空的话不需要新建
      if (state.messageList.length === 0) return
      // 如果当前的对话已经是空的，也不要新建
      const currentMsgGroup = state.messageList.find(item => item.key === state.selectedKey)
      if (currentMsgGroup && currentMsgGroup.chatList.length === 0) return
      // 新建一个对话
      const key = Date.now() + ''
      const newMsgGroupObj = {
        key,
        label: '新对话',
        timestamp: Date.now(),
        group: formatDate('YYYY-MM-DD'), // 用日期来分组
        chatList: []
      }
      state.messageList.unshift(newMsgGroupObj)
      state.selectedKey = key
    }),
    // 把这个对话的状态改成input为true
    setConversationInput: produce((state: initialStateType, action: { payload: string }) => {
      const handleSelectkey = action.payload
      const existingMessage = state.messageList.find(item => item.key === handleSelectkey)
      if (existingMessage) {
        existingMessage.isInput = !existingMessage.isInput
      }
    }),
    // 重命名对话label
    renameConversation: produce(
      (
        state: initialStateType,
        action: {
          payload: {
            key: string
            label: string
          }
        }
      ) => {
        const { key, label } = action.payload
        const existingMessage = state.messageList.find(item => item.key === key)
        if (existingMessage) {
          existingMessage.label = label
        }
      }
    ),
    // 删除对话
    deleteConversation: produce((state: initialStateType, actions: { payload: string }) => {
      // 要删除的key
      const deleteKey = actions.payload
      // 找到当前选中的对话
      const currentIndex = state.messageList.findIndex(item => item.key === deleteKey)
      // 如果要删除的key是选中的key，则需要切换选中的key
      if (deleteKey === state.selectedKey) {
        if (currentIndex >= 0) {
          // 判断如果选中的是第一个，则选中下一个，如果已经是最后一个，则选中前一个，如果只有一个，则重置key
          if (currentIndex === 0) {
            // 如果是第一个，则选中下一个
            if (state.messageList.length > 1) {
              state.selectedKey = state.messageList[1].key
            } else {
              // 如果只有一个，则重置key
              state.selectedKey = ''
            }
          } else if (currentIndex === state.messageList.length - 1) {
            // 如果是最后一个，则选中前一个
            state.selectedKey = state.messageList[currentIndex - 1].key
          }
        }
      }
      // 删除当前对话，然后判断
      state.messageList.splice(currentIndex, 1)
    }),
    // 修改选中模型
    changeSelectedModel: produce((state: initialStateType, action: { payload: string }) => {
      state.selectedModel = action.payload
    })
  }
})
// 每个 case reducer 函数会生成对应的 Action creators
export const {
  addMessage,
  addSystemMessage,
  changeSelectedKey,
  setLoading,
  addConversation,
  setConversationInput,
  renameConversation,
  deleteConversation,
  changeSelectedModel
} = messageSlice.actions

export default messageSlice.reducer
